package com.iflytek.edu.pdc.uc.elasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.iflytek.edu.pdc.uc.elasticsearch.support.Builder.QueryCondition;
import com.iflytek.edu.pdc.uc.elasticsearch.support.Param;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @Description:
 * @author: liux
 * @date: 2019/3/7 3:31 PM
 */
@Service
public class ElasticsearchBaseService {


    private static final Logger logger= LoggerFactory.getLogger(ElasticsearchBaseService.class);
    @Resource
    private TransportClient transportClient;

    /**
     * 精确查询(类似mysql多个and) 分页 排序
     *
     * @param index        索引
     * @param type         type 名
     * @param queryCondition 构建BoolQueryBuilder
     * @param sortFiled    排序字段
     * @param sort         排序
     * @param entityClass  实体
     * @param param        分页参数(兼容 basis 分页实体)
     * @param <T>
     * @return
     */
    public <T> List<T> searchTerm(String index, String type,
                                            QueryCondition queryCondition,
                                            String sortFiled,
                                            String sort,
                                            Class<T> entityClass,Param param) {

        if (!StringUtils.isNotEmpty(index) || !StringUtils.isNotEmpty(type)) {
            return null;
        }
        // 构建查询条件
        QueryBuilder queryBuilder=queryCondition.getQueryBuilder();
        SearchResponse searchResponse;
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes(type)
                .setSearchType(SearchType.DEFAULT)
                .setFrom(param.getPageIndex())
                .setSize(param.getLimit());
        if (StringUtils.isNotEmpty(sortFiled)) {
            if (sort.toUpperCase().equals("ASC")) {
                searchRequestBuilder.addSort(sortFiled, SortOrder.ASC);
            } else {
                searchRequestBuilder.addSort(sortFiled, SortOrder.DESC);
            }
        }
        searchResponse = searchRequestBuilder.setQuery(queryBuilder).execute().actionGet();
        logger.info(queryBuilder.toString());
        System.out.println(queryBuilder.toString());
        SearchHits hits = searchResponse.getHits();
        List<T> list = new ArrayList<T>();
        for (SearchHit hit : hits) {
            T o = JSON.parseObject(hit.getSourceAsString(), entityClass);
            list.add(o);
        }
        return list;

    }



    /**
     * 通配符Wildcard查询(类似mysql多个and  like) 分页 排序
     *
     * @param index        索引
     * @param type         type 名
     * @param queryCondition 构建BoolQueryBuilder
     * @param sortFiled    排序字段
     * @param sort         排序
     * @param entityClass  实体
     * @param param        分页参数(兼容 basis 分页实体)
     * @param <T>
     * @return
     */
    public <T> List<T> searchWildcard(String index, String type,
                                            QueryCondition queryCondition,
                                            String sortFiled,
                                            String sort,
                                            Class<T> entityClass,Param param) {

        if (!StringUtils.isNotEmpty(index) || !StringUtils.isNotEmpty(type)) {
            return null;
        }

        // 构建查询条件
        QueryBuilder queryBuilder;
        SearchResponse searchResponse;
        queryBuilder = queryCondition.getQueryBuilder();
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes(type)
                .setSearchType(SearchType.DEFAULT)
                .setFrom(param.getPageIndex())
                .setSize(param.getLimit());
        if (StringUtils.isNotEmpty(sortFiled)) {
            if (sort.toUpperCase().equals("ASC")) {
                searchRequestBuilder.addSort(sortFiled, SortOrder.ASC);
            } else {
                searchRequestBuilder.addSort(sortFiled, SortOrder.DESC);
            }
        }
        searchResponse =searchRequestBuilder
                .setQuery(queryBuilder)
                .execute().actionGet();
        logger.info(queryBuilder.toString());
        System.out.println(queryBuilder.toString());
        SearchHits hits = searchResponse.getHits();
        List<T> list = new ArrayList<T>();
        for (SearchHit hit : hits) {
            T o = JSON.parseObject(hit.getSourceAsString(), entityClass);
            list.add(o);
        }
        return list;

    }


}
